<template>
  <div class="route-debug">
    <h2>路由调试页面</h2>

    <div class="debug-section">
      <h3>当前路由信息</h3>
      <el-card>
        <pre>{{ routeInfo }}</pre>
      </el-card>
    </div>

    <div class="debug-section">
      <h3>用户信息</h3>
      <el-card>
        <pre>{{ userInfo }}</pre>
      </el-card>
    </div>

    <div class="debug-section">
      <h3>操作</h3>
      <el-card>
        <el-button type="primary" @click="refreshRoutes">刷新路由</el-button>
        <el-button @click="checkRoutes">检查路由状态</el-button>
        <el-button @click="forceUpdateSidebar">强制更新侧边栏</el-button>
      </el-card>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { updateRouter } from '@/router'
import { checkRoutesLoaded } from '@/utils/route-updater'

export default {
  name: 'RouteDebug',
  computed: {
    ...mapGetters(['name', 'avatar', 'roles']),
    routeInfo() {
      const router = this.$router
      if (!router) return '路由器未找到'

      return {
        currentRoute: router.currentRoute,
        routes: router.options.routes,
        routeCount: router.options.routes.length,
        hasRoutesLoaded: checkRoutesLoaded()
      }
    },
    userInfo() {
      return {
        name: this.name,
        avatar: this.avatar,
        roles: this.roles,
        hasToken: !!this.$store.state.user.token
      }
    }
  },
  methods: {
    async refreshRoutes() {
      try {
        this.$message.info('开始刷新路由...')
        await updateRouter()
        this.$message.success('路由刷新成功')

        // 触发侧边栏更新
        setTimeout(() => {
          const event = new CustomEvent('sidebar-update')
          window.dispatchEvent(event)
        }, 100)
      } catch (error) {
        this.$message.error('路由刷新失败: ' + error.message)
      }
    },
    checkRoutes() {
      const loaded = checkRoutesLoaded()
      if (loaded) {
        this.$message.success('路由已正确加载')
      } else {
        this.$message.warning('路由可能未正确加载')
      }
    },
    forceUpdateSidebar() {
      const event = new CustomEvent('sidebar-update')
      window.dispatchEvent(event)
      this.$message.info('已触发侧边栏更新')
    }
  },
  mounted() {
    console.log('路由调试页面已加载')
    console.log('当前路由信息:', this.routeInfo)
    console.log('用户信息:', this.userInfo)
  }
}
</script>

<style scoped>
.route-debug {
  padding: 20px;
}

.debug-section {
  margin-bottom: 20px;
}

pre {
  background: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
  overflow-x: auto;
}

.el-card {
  margin-top: 10px;
}
</style>
